package com.mobi.Survey.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.mobi.Survey.adapters.CustomAdapterCategories;
import com.mobi.Survey.lib.activities.AbstractScreen;
import com.mobi.Survey.lib.activities.LoginScreen;
import com.mobi.Survey.map.SearchTask.SearchComplete;
import com.mobi.Survey.map.SearchTask.SearchContext;

public class MapLogin extends LoginScreen implements SearchComplete {

	// private View btnSkip;

	private static List<MapMarker> mapPoints = new ArrayList<MapMarker>();
	private static SearchContext serachContext = new SearchContext();
	private static Map<String, Bitmap> userListIcons = new HashMap<String, Bitmap>();

	public static Map<String, Bitmap> getUserListIcons() {
		return userListIcons;
	}

	public static void setUserListIcons(Map<String, Bitmap> userListIcons) {
		MapLogin.userListIcons = userListIcons;
	}

	private EditText editAddress;
	private View btnUserClear;
	private View btnClearAddress;
	private ListView lvCategories;
	private CustomAdapterCategories adapter;

	private UserListContainer containerUserList;
	private MapContainer containerMap;

	private View containerSearch;

	private boolean listItemClick = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		hideKeaboard = true;
		super.onCreate(savedInstanceState);

		editAddress.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (editAddress.getText().length() > 0
						&& btnClearAddress.getVisibility() == View.GONE) {
					btnClearAddress.setVisibility(View.VISIBLE);
				} else if (editAddress.getText().length() == 0) {
					btnClearAddress.setVisibility(View.GONE);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}

		});

		lvCategories.setAdapter(adapter);

		lvCategories.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position,
					long id) {

				Category category = adapter.getItem(position);

				List<Category> subCategories = category.getSubCategories();
				if (null == subCategories || subCategories.size() == 0) {
					listItemClick = true;
					editUserId.setText(category.getName());
					return;
				}
				editUserId.setText(category.getName());

				adapter.setData(subCategories);
				adapter.notifyDataSetChanged();

			}
		});

		editAddress.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {

					showAddressDialogue();
				}

			}
		});
		editAddress.setKeyListener(null);

		int id = AbstractScreen.getMapTabId(this);

		if (id == 2) {

			this.containerMap.makeGone();
			this.makeGone();
			this.containerUserList.makeVisible();

		} else if (id == 22) {

			this.containerMap.refresh();
			this.containerMap.makeVisible();
			this.makeGone();
			this.containerUserList.makeGone();

		} else {

			this.containerMap.makeGone();
			this.makeVisible();
			this.containerUserList.makeGone();
		}

		setListnerEditUser();
		
		filLSearchFields(serachContext);

	}

	private void showAddressDialogue() {
		Intent i = new Intent(MapLogin.this, AddressDialogue.class);
		i.putExtra("city", serachContext.city);
		i.putExtra("country", serachContext.country);
		i.putExtra("state", serachContext.state);
		i.putExtra("zip", serachContext.zip);
		startActivityForResult(i, 10);
	}

	public static SearchContext getSerachContext() {
		return serachContext;
	}

	private void setListnerEditUser() {

		editUserId.setText("");

		editUserId.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (editUserId.getText().length() > 0
						&& btnUserClear.getVisibility() == View.GONE) {
					btnUserClear.setVisibility(View.VISIBLE);
				} else if (editUserId.getText().length() == 0) {
					btnUserClear.setVisibility(View.GONE);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (listItemClick) {
					listItemClick = false;
					return;
				}

				serachAndRefreshList(s.toString());
			}
		});

	}

	private void serachAndRefreshList(String searchStr) {
		searchStr = searchStr.trim();
		if (searchStr.length() == 0) {
			adapter.setData(MapHelper.categories);
			adapter.notifyDataSetChanged();
			return;
		}
		searchStr = searchStr.toLowerCase();
		List<Category> searched = new ArrayList<Category>();

		for (Category cat : MapHelper.categories) {

			Category clone = null;
			if (cat.getName().toLowerCase().contains(searchStr)) {
				clone = (Category) cat.clone();
				if (!searched.contains(clone))
					searched.add(clone);

			}

			for (Category subCat : cat.getSubCategories()) {
				if (subCat.getName().toLowerCase().contains(searchStr)) {

					Category subClone = (Category) subCat.clone();

					if (!searched.contains(clone))
						searched.add(subClone);
				}
			}

		}

		adapter.setData(searched);
		adapter.notifyDataSetChanged();
	}

	@Override
	protected void onStart() {

		super.onStart();

	}

	@Override
	protected void onRestart() {

		super.onRestart();

	};

	// private boolean findLocationCalled = false;
	// private LatLongToAddressTask latLongTask;

	// private void findUserLocation() {
	//
	// new LocationService(new OnLocationUpdate() {
	//
	// @Override
	// public void onLocationRetrived(Location location) {
	//
	// latLongTask = new LatLongToAddressTask();
	// latLongTask.execute(location);
	//
	// }
	//
	// }).run(MapLogin.this);
	//
	// }

	// private class LatLongToAddressTask extends AsyncTask<Location, Void,
	// Void> {
	// private Address address;
	//
	// @Override
	// protected void onPreExecute() {
	//
	// super.onPreExecute();
	// if (isCancelled()) {
	// return;
	// }
	// showLongToast(getString(R.string.get_your_location));
	// }
	//
	// @Override
	// protected void onPostExecute(Void result) {
	//
	// super.onPostExecute(result);
	// if (null != address && !isCancelled()) {
	// fillAddressInEditBox(address);
	// findLocationCalled = true;
	// } else {
	// showAlert(getString(R.string.location_error));
	// }
	// findViewById(R.id.pbGettingAddress).setVisibility(View.INVISIBLE);
	//
	// }
	//
	// @Override
	// protected Void doInBackground(Location... params) {
	//
	// Location location = params[0];
	// if (null != location && !isCancelled()) {
	// address = MapHelper.getCurrentLocationViaJSON(
	// location.getLatitude(), location.getLongitude());
	// }
	// return null;
	// }
	//
	// }

	private void filLSearchFields(SearchContext sc) {
		if (null != sc) {
			editAddress.setText("");
			editUserId.setText("");
			if (sc.country != null
					&& sc.country.length() > 0) {
				editAddress.append(sc.country);
				if (sc.city != null && sc.city.length() > 0) {
					editAddress.append(" ");
				}
			}
			if (sc.city != null && sc.city.length() > 0) {

				editAddress.append(sc.city);
				if (sc.zip != null && sc.zip.length() > 0) {
					editAddress.append(" ");
				}
			}
			if (sc.zip != null && sc.zip.length() > 0) {
				editAddress.append(sc.zip);
				if (sc.state != null
						&& sc.state.length() > 0) {
					editAddress.append(" ");
				}
			}
			if (sc.state != null && sc.state.length() > 0) {
				editAddress.append(" "+sc.state);
			}
			
			if(sc.keyword != null && sc.keyword.length()>0){
				editUserId.setText(sc.keyword);
			}

		}
	}

	public final void makeVisible() {
		containerSearch.setVisibility(View.VISIBLE);
	}

	public final void makeGone() {
		containerSearch.setVisibility(View.GONE);
	}

	@Override
	protected void initUiVars() {

		// txtErrorLogin = (TextView) findViewById(R.id.txtErrorLogin);
		editUserId = (EditText) findViewById(R.id.editUserId);

		editAddress = (EditText) findViewById(R.id.editAddress);
		btnClearAddress = findViewById(R.id.btnClearAddress);
		btnUserClear = findViewById(R.id.btnUserClear);
		lvCategories = (ListView) findViewById(R.id.lvCategories);
		// editCountry = (EditText) findViewById(R.id.editCountry);
		// editZip = (EditText) findViewById(R.id.editZip);
		// editState = (EditText) findViewById(R.id.editState);
		// editCity = (EditText) findViewById(R.id.editCity);
		containerSearch = findViewById(R.id.containerSearch);

		containerMap = new MapContainer(this);

		containerUserList = new UserListContainer(this, containerMap);
		containerUserList.setupViews();

		adapter = new CustomAdapterCategories(this, MapHelper.categories);

	}

	public static List<MapMarker> getMapPoints() {
		return mapPoints;
	}

	public static void setMapPoints(List<MapMarker> mapPoints) {
		MapLogin.mapPoints = mapPoints;
	}

	@Override
	protected int getLayoutId() {
		return R.layout.map_login;

	}

	private boolean isClicked = false;

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btnSearch && !isClicked
				&& MapHelper.isGooglePlayServicesInstalled(this)) {

			onSearchClick();

		} else if (id == R.id.btnUserList) {
			this.makeGone();
			this.containerMap.makeGone();
			this.containerUserList.makeVisible();

		} else if (id == R.id.btnMap) {
			this.makeGone();
			this.containerMap.makeVisible();
			this.containerUserList.makeGone();

		} else if (id == R.id.btnBack) {

			this.makeVisible();
			mapPoints.clear();
			this.containerMap.makeGone();
			this.containerMap.refresh();
			this.containerUserList.makeGone();
			this.containerUserList.refresh();

		}

		else if (id == R.id.btnSkip) {
			onSkipClick();

		} else if (id == R.id.btnUserClear) {
			editUserId.setText("");

		} else if (id == R.id.btnClearAddress) {
			editAddress.setText("");
			serachContext.city = "";
			serachContext.state = "";
			serachContext.country = "";
			serachContext.zip = "";

		} else if (id == R.id.editAddress) {
			showAddressDialogue();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent i) {

		super.onActivityResult(requestCode, resultCode, i);

		if (requestCode == 10 && resultCode == RESULT_OK && null != i) {
			Bundle b = i.getExtras();

			String country = b.getString("country");
			String zip = b.getString("zip");
			String state = b.getString("state");
			String city = b.getString("city");

			serachContext.country = country;
			serachContext.city = city;
			serachContext.zip = zip;
			serachContext.state = state;

 
			filLSearchFields(serachContext);
		}

	}

	private void onSearchClick() {

		serachContext.startIndex = 0;
		serachContext.pageSize = Integer.parseInt(getResources().getString(
				R.string.page_size));
		serachContext.keyword = editUserId.getText().toString();
		SearchTask task = new SearchTask(this, serachContext);
		task.setSearchComplete(this);
		task.execute();

		isClicked = false;

	}

	@Override
	protected void onRelease() {

		if (AbstractScreen.getMapTabId(this) == -1) {

			for (String key : userListIcons.keySet()) {
				Bitmap b = userListIcons.get(key);
				if (null != b && !b.isRecycled()) {
					b.recycle();
				}

			}
			userListIcons.clear();
			serachContext = new SearchContext();

		}
	}
 
	private long prevClick = 0;

	@Override
	public void onBackPressed() {
		long curTime = System.currentTimeMillis();
		if (prevClick == 0 || (curTime - prevClick) > MapTabHost.CLOSE_TIME) {
			prevClick = curTime;
			Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT)
					.show();
		} else {
			onRelease();
			super.onBackPressed();
		}

	}

	@Override
	public void onComplete(List<MapMarker> mapMarkers) {
		if (serachContext.startIndex == (serachContext.totaCount - 1)) {
			this.containerUserList.getBtnLoadMore().setVisibility(View.GONE);

		} else if (this.containerUserList.getBtnLoadMore().getVisibility() == View.GONE) {
			this.containerUserList.getBtnLoadMore().setVisibility(View.VISIBLE);
		}
		mapPoints = mapMarkers;

		this.containerMap.setupViews();
		this.containerMap.makeGone();
		this.makeGone();
		this.containerUserList.makeVisible();
		this.containerUserList.refresh();
		new SearchTask.IconDownloadTask().execute(containerUserList
				.getAdapter());

	}

}
